import NProgress from "nprogress";
// 路径前缀
const BASE_URL = "http://121.199.14.205:3000/api";

const http = {
  get(url, params) {
    // 这里接受到的params是对象
    // url是/rated/list  params是{a: 3,b: 4}   ->    /rated/list?a=3&b=4
    if (params) {
      url += "?";
      let arr = [];
      for (const key in params) {
        arr.push(key + "=" + params[key]); // ["a=3", "b=4"]
        // url += key + "=" + params[key] + "&";
      }
      url += arr.join("&"); // /rated/list?a=3&b=4
    }
    return new Promise((resolve) => {
      return fetch(BASE_URL + url)
        .then((response) => response.json())
        .then((res) => {
          if (res.status === 0) {
            resolve(res);
          }
        });
    });
  },
  post(url, data) {
    NProgress.start();
    return new Promise((resolve) => {
      return fetch(BASE_URL + url, {
        body: JSON.stringify(data),
        headers: {
          "content-type": "application/json",
        },
        method: "POST",
      })
        .then((response) => response.json())
        .then((res) => {
          NProgress.done();
          if (res.status === 0) {
            resolve(res);
          }
        });
    });
  },
};

export default http;
